const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
//创建服务器
http.createServer((req, res) => {
    // 回应登录
    res.setHeader('content-type', 'text/html;charset=utf-8');//设置响应头
    if (req.url.startsWith('/login') && req.method == 'GET') {
        let data = fs.readFileSync(path.join(__dirname, '/login.html'));
        res.end(data);
    }//回应dologin
    else if (req.url.startsWith('/dologin') && req.method == 'GET') {
        // 获取提交的账户和密码

        let { query: { username, password } } = url.parse(req.url, true)
        let data = JSON.parse(fs.readFileSync(path.join(__dirname, '/persons.json')));
        let islogin = data.find(value => value.username == username && value.password == password);

        if (islogin) {
            res.end('登录成功')
        } else {
            res.end('用户或密码输入错误')
        }
    }
    else if (req.url.startsWith('/register') && req.method == 'GET') {
        let data = fs.readFileSync(path.join(__dirname, '/register.html'));
        res.end(data);
    }
    // 回应doregister
    else if (req.url.startsWith("/doregister") && req.method == 'GET') {
        // 获取提交的账户和密码
        let { query: { username, password } } = url.parse(req.url, true)
        let data = JSON.parse(fs.readFileSync(path.join(__dirname, '/persons.json')));
        let islogin = data.find(value => value.username == username && value.password == password);

        if (islogin) {
            res.end('已注册')
        } else {
            data.push({username, password});
            fs.writeFileSync(path.join(__dirname,'/persons.json'),JSON.stringify(data));
            res.end('注册成功')
        }
    } 
}).listen(2500, () => {
    console.log('已开启');
})